package com.ruoyi.web.controller.notify;

import com.ruoyi.common.json.JsonMap;
import com.ruoyi.common.json.JsonUtil;
import com.ruoyi.common.aliyun.DingCallbackCrypto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class NotifyDingDingController {


    /**
     * @return
     */
    @PostMapping("/notify/dingding/callback")
    public Object callback(HttpServletRequest request,
                           @RequestParam(value = "msg_signature", required = false) String msg_signature,
                           @RequestParam(value = "timestamp", required = false) String timeStamp,
                           @RequestParam(value = "nonce", required = false) String nonce,
                           @RequestBody(required = false) JsonMap json) {

        try {
            // 1. 从http请求中获取加解密参数

            // 2. 使用加解密类型
            // Constant.OWNER_KEY 说明：
            // 1、开发者后台配置的订阅事件为应用级事件推送，
            //      此时OWNER_KEY为应用的APP_KEY（企业内部应用）或SUITE_KEY（三方应用）。
            // 2、调用订阅事件接口订阅的事件为企业级事件推送，
            //      此时OWNER_KEY为：企业的CORP_ID（企业内部应用）或SUITE_KEY（三方应用）
            String encryptMsg = json.getString("encrypt");
            String decryptMsg = DingCallbackCrypto.getDecryptMsg(msg_signature, timeStamp, nonce, encryptMsg);
            log.debug("====decryptMsg:" + decryptMsg);
            // 3. 反序列化回调事件json数据
            JsonMap dataJson = JsonUtil.toJsonMap(decryptMsg);
            log.debug("========={}", dataJson);
            assert dataJson != null;
            String eventType = dataJson.getString("EventType");
            //通讯录事件
            eventConvert(dataJson, eventType);

            // 5. 返回success的加密数据
            return DingCallbackCrypto.getEncryptedMap("success");

        } catch (DingCallbackCrypto.DingTalkEncryptException e) {
            log.error("钉钉事件解密error", e);
        }
        return null;
    }


    public static void main(String[] args) throws DingCallbackCrypto.DingTalkEncryptException {
//        String appkey = "dingw3ugw0tlpgxf0ntl";
//        String aesKey = "8u2SSPF6cRN4BwHXodZCrZ6t1G9TdgaiyOTm9zjEuAD";
//        String token = "ZQWGMXHdDEH0GxYoAz6siL1l56thvF4GPVIpw33UAAcVcpmlh";
//        DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(token, aesKey, appkey);
//        String encryptMsg = "Ijf4G85srob3qgt9xEzrfQIbUC8buWxBxTAPgJbVpjERGa8rET6hBmJubC7gYZl8xthYkOsVtRqmuLGjem6W83stFPIqsiPEqSd0la1nP3ROZqhCtuJI5hxvC2l62YHl";
//        String decryptMsg = callbackCrypto.getDecryptMsg(encryptMsg);
//        System.out.println(decryptMsg);
    }

    /**
     * 通讯录事件
     *
     * @param dataJson
     * @param eventType
     */
    private void eventConvert(JsonMap dataJson, String eventType) {
        String corpId = dataJson.getString("CorpId");
        if ("ding63f275d3e17d9b0235c2f4657eb6378f".equals(corpId)) {
            //力诺总公司事件
            switch (eventType) {
                default:
                    // 添加其他已注册的
                    log.info("发生了：" + eventType + "事件");
                    break;
            }
        }

    }
}
